package com.codemonkey.lq.common.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public final class FileHelper {

	private FileHelper() {
		super();
	}

	
	/**
	 * 写到这里是为了备份
	 * @param filePathByClassLoader 以class path为路径, 
	 * @return
	 */
	public static File toFile(String filePathByClassLoader) {
		//		File file = FileUtils.toFile(Resources
		//				.getResource(filePathByClassLoader));
		// 		return file;
		
		return null;
	}

	/**
	 * 向文件末尾添加内容
	 * @param fileFullPath
	 * @param content
	 */
	public static void appendContent(final String fileFullPath, String content) {
		// From https://zhuanlan.zhihu.com/p/28140439?utm_source=qq&utm_medium=social

		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(fileFullPath, true));
			out.write(content);
		} catch (IOException e) {
			// error processing code  
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static boolean exist(String filePath) {
		if (StringHelper.isEmpty(filePath)) {
			return false;
		}

		return (new File(filePath).exists());
	}

	/**
	 * 将传入的参数以 File.separator 进行隔开, 尾部不带 File.separator
	 * @param filePathComponents
	 * @return
	 */
	public static String concatFilePath(String... filePathComponents) {
		String result = filePathComponents[0];
		for (int i = 1; i < filePathComponents.length; i++) {
			if ((!result.endsWith(File.separator)) && (!result.endsWith("/"))) {
				result += File.separator;
			}
			result += filePathComponents[i];
		}

		return result;
	}

	/**
	 * 只针对文件, 不针对文件夹！
	 * @param fileFullPath
	 * @return
	 */
	public static boolean makeSureFileExist(String fileFullPath) {
		File file = new File(fileFullPath);

		if (file.exists()) {
			return true;
		}

		try {
			file.createNewFile();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 复制单个文件中的内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					//System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf/ff
	 * @return boolean
	 */
	public static void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath + "/"
							+ (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();

		}

	}

	///根据文件路径直接返回文件流
	public static InputStreamReader getInputStreamReader(String path) throws java.io.IOException {
		java.io.InputStreamReader isr = null;
		String encode = getFileEncode(path);
		if (encode.equals("")) {
			isr = new java.io.InputStreamReader(

			new java.io.FileInputStream(path));
		} else {
			isr = new java.io.InputStreamReader(

			new java.io.FileInputStream(path), encode);
		}

		return isr;
	}

	/**  根据文件路径返回编码格式
	 * 根据文本文件开头几个字节来判断文件的编码格式（txt文件的开头会多出几个字节，分别是FF、FE（Unicode）,FE、FF（Unicode big endian）,EF、BB、BF（UTF-8））
	 * 例如 对于UTF-8编码格式的文本文件，其前3个字节的值就是-17、-69、-65
	 * 目前可以测试出来的是UTF-8,是带BOM的
	 * @param path
	 * @return
	 * @note <br> 
	 * 	1. http://www.cnblogs.com/yejg1212/p/3402322.html (java自动探测文件的字符编码) <br>
	 *  2. http://www.cnblogs.com/liinux/p/5522019.html (Cpdetector编码识别) <br>
	 */
	public static String getFileEncode(String path) {
		java.io.RandomAccessFile raf = null;
		String encode = "";
		try {
			raf = new java.io.RandomAccessFile(path, "r");
			raf.seek(0);
			int flag1 = 0;
			int flag2 = 0;
			int flag3 = 0;
			if (raf.length() >= 2) {
				flag1 = raf.readUnsignedByte();
				flag2 = raf.readUnsignedByte();
			}
			if (raf.length() >= 3) {
				flag3 = raf.readUnsignedByte();
			}
			encode = getEncode(flag1, flag2, flag3);
		} catch (java.io.IOException e) {
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return encode;

	}

	private static String getEncode(int flag1, int flag2, int flag3) {
		String encode = "";
		//txt文件的开头会多出几个字节，分别是:
		// FF、FE（Unicode）,
		// FE、FF（Unicode big endian）,
		// EF、BB、BF（UTF-8）
		// UTF-8 无BOM  似乎是 51  50 49   --测试失败！！！！！！
		if (flag1 == 255 && flag2 == 254) {
			encode = "Unicode";
		} else if (flag1 == 254 && flag2 == 255) {
			encode = "UTF-16";
		} else if (flag1 == 239 && flag2 == 187 && flag3 == 191) {
			encode = "UTF-8";
		}

		return encode;
	}
}
